//
//  Story.m
//  iPing
//
//  Created by Thomas on 8/4/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "StoryController.h"


@implementation StoryController
- (id)init 
{ 
    if (![super initWithWindowNibName:@"StoryController"]) 
        return nil; 
	theStoryList	= [[SGStoryList alloc] init];
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
	[nc addObserver:self 
           selector:@selector(displayText:) 
               name:TCSGLabelNot
             object:nil]; 
	
	li=0;
    return self; 
} 
- (void)displayText:(NSNotification *)note
{
	[labelField setStringValue:[note object]];
}
- (IBAction)addToLibrary:(id)pId
{
	[theStoryList addCheckedToLibrary];
}
- (IBAction)changeHost:(id)pId
{
	switch ([[hostButton objectValue] intValue]) 
	{
		case 0:
			//NSLog(@"case: 0");
			[imageWell setImage:[NSImage imageNamed:@"SOLlogo.png"]];
			break;
		case 1:
			[imageWell setImage:[NSImage imageNamed:@"litlogo.png"]];
			break;
		default:
			break;
	}
}
- (IBAction)removeStoryFromTable:(id)pId
{
	[theStoryList removeItemAtRow:[tableView selectedRow]];
	[tableView reloadData];
}

- (IBAction)moveDownInTable:(id)pId
{
	[theStoryList moveItemAtRow:[tableView selectedRow] value:1];
	int row = [tableView selectedRow];
	if(row < ([theStoryList numberOfItems]-1))
	{
		int i = [tableView selectedRow];
		[tableView selectRow:(i+1) byExtendingSelection:NO];
	}
	[tableView reloadData];
}

- (IBAction)printToLog:(id)pId
{
	NSString *a=[theStoryList combineAll];
	[a writeToFile:[[saveField stringValue] stringByAppendingPathComponent:[[compileField stringValue] stringByAppendingPathExtension:@"html"]] atomically:YES encoding:NSUTF8StringEncoding error:nil];
	}

- (IBAction)moveUpInTable:(id)pId
{
	//int action=-1;
	int row = [tableView selectedRow];
	[theStoryList moveItemAtRow:row value:-1];

	if(row != 0)
	{
		int i = [tableView selectedRow];
		[tableView selectRow:(i-1) byExtendingSelection:NO];
	}
	[tableView reloadData];
}

- (IBAction)doAddRandom:(id)pId
{
	//li++;
	[theStoryList addStory:@"hello" 
				 withTitle:@"hello" 
				withAuthor:@"hello" 
				  withHost:@"hello" 
					withID:[NSString stringWithFormat:@"%i",11,nil] 
				 withCheck:[NSNumber numberWithBool:YES]];
	[tableView reloadData];

	NSString *hello = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://ficwad.com/story/116581"]];
	[hello writeToFile:@"/Users/tom/Desktop/hello.html" atomically:YES];
	//NSString *tempString = [NSString stringWithContentsOfFile:@"/Users/tom/litAuthorEx.html"];
	//[theStoryList writeData];
	//[TCSGgetSOLstory writeDefaultNotification];
	/*if(running)
	{
		[self stopRunning];
		[TCSGGeneralMethods setLabelField:@"Starting"];
	}
	else
	{
		[self startRunning];
		[TCSGGeneralMethods setLabelField:@"Finished"];
	}*/
	}
- (void)getLITAuthor:(NSString *)authorID
{
	NSString *tempString = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.literotica.com/stories/memberpage.php?uid=%@&page=submissions",authorID,nil]]];
	[labelField setStringValue:@"get Lit Author Stories"];
	NSArray *tempArray = [tempString componentsSeparatedByString:@"href=\"http://www.literotica.com/stories/showstory.php?id="];
	//NSLog(@"%@",[tempArray objectAtIndex:1]);
	int i;
	NSMutableArray *tempArray2 = [[NSMutableArray alloc] init];
	for (i=1;i<[tempArray count];i++)
	{
		NSRange tempRange = [[tempArray objectAtIndex:i] rangeOfString:@"\">"];
		[tempArray2 addObject:[[tempArray objectAtIndex:i] substringToIndex:tempRange.location]];
	}
	for(i=0;i<[tempArray2 count];i++)
	{
		[labelField setStringValue:[NSString stringWithFormat:@"gettingStoryID:%@",[tempArray2 objectAtIndex:i]]];
		[self getLITStory:[tempArray2 objectAtIndex:i]];
	}
	
	
}
- (void)getLITStory:(NSString *)storyID
{
	NSString *page = [NSString stringWithContentsOfURL:
					  [NSURL URLWithString:
					   [NSString stringWithFormat:@"http://www.literotica.com/stories/showstory.php?id=%@",storyID,nil]]];
	[page writeToFile:@"/Users/tom/Desktop/1.html" atomically:YES];
	NSRange titleStart		= [page rangeOfString:@"<title>"];
	NSRange titleEnd		= [page rangeOfString:@"</title>"];
	NSRange titleRange;
	titleRange.location		= titleStart.location+titleStart.length;
	titleRange.length		= titleEnd.location-titleRange.location;
	NSArray *titleArray		= [[page substringWithRange:titleRange] componentsSeparatedByString:@" - "];
	//NSLog(@"titleArray:%@",titleArray);
	NSString *genre			= [titleArray objectAtIndex:1];
	NSString *host			= [titleArray objectAtIndex:2];
	NSString *title			= [titleArray objectAtIndex:0];
	
	NSRange authorStart		= [page rangeOfString:@"submissions\">"];
	NSString *authorString  = [page substringFromIndex:(authorStart.location + authorStart.length)];
	NSRange authorEnd		= [authorString rangeOfString:@"</a><span>"];
	NSString *author		= [authorString substringToIndex:(authorEnd.location)];
	//NSLog(@"title:%@",title);
	//NSLog(@"author:%@",author);
	//NSLog(@"host:%@",host);
	NSString *story = [self getLITStoryProper:storyID withPageOne:page];
	story = [NSString stringWithFormat:@"<html><head><title>%@</title></head><body><h1 class=\"chapter\">%@</h1>\n%@</body></html>",title,story,title,nil];
	[theStoryList addStory:story 
				 withTitle:title 
				withAuthor:author 
				  withHost:host 
					withID:storyID 
				 withCheck:[NSNumber numberWithBool:TRUE]];
	NSMutableDictionary *extraInfo = [[self getLITMoreInfoForPage:page storyID:storyID] mutableCopy];
	[extraInfo setObject:genre forKey:@"Genre"];
	[theStoryList addExtraInfo:extraInfo forRow:([theStoryList numberOfItems]-1)];
	//[theStoryList printDict];
	[tableView reloadData];
	
	
	//<div id="content">
}
- (NSDictionary *)getLITMoreInfoForPage:(NSString *)page storyID:(NSString *)storyID
{
	NSRange descStart	= [page rangeOfString:@"<meta name=\"description\" content=\""];
	NSRange tempRange	= {descStart.location+descStart.length,([page length]-(descStart.location+descStart.length))};
	NSRange descEnd		= [page rangeOfString:@"\"  />" options:NSCaseInsensitiveSearch range:tempRange];
	NSRange descRange	= {(descStart.location+descStart.length),(descEnd.location-(descStart.location+descStart.length))};
	
	NSMutableDictionary *extraInfo	= [[NSMutableDictionary alloc] initWithObjectsAndKeys:[page substringWithRange:descRange],SUMMARYKEY,nil];
	return extraInfo;
}
- (NSString *)getLITStoryProper:storyID withPageOne:page
{
	NSRange storyStart	= [page rangeOfString:@"<div id=\"content\">"];
	NSRange pageEnd		= [page rangeOfString:@"<div id=\"storypager\">"];
	NSString *story		=@"multiple";
	if(pageEnd.location ==NSNotFound)
	{
		NSRange tempRange	= {storyStart.location,([page length]-storyStart.location)};
		/*tempRange.location = storyStart.location
		tempRange.length*/
		pageEnd				= [page rangeOfString:@"<div class=" options:NSCaseInsensitiveSearch range:tempRange ];
		NSRange storyRange	= {(storyStart.location+storyStart.length),(pageEnd.location-storyStart.location-storyStart.length) };
		story= [page substringWithRange:storyRange];
	}
	else
	{
		NSRange storyRange		= {(storyStart.location+storyStart.length),(pageEnd.location-storyStart.location-storyStart.length) };
		story = [page substringWithRange:storyRange];
		//Need to get storyParser
		NSMutableArray * pagesArray = [[page componentsSeparatedByString:[NSString stringWithFormat:@"<a href=\"http://www.literotica.com/stories/showstory.php?id=%@&amp;page=",storyID,nil]] mutableCopy];
		[pagesArray removeObjectAtIndex:0];
		int i;
		for(i=0;i<[pagesArray count];i++)
		{
			NSRange tempRange = [[pagesArray objectAtIndex:i] rangeOfString:@"\">"];
			NSRange tempRange2 = {0,tempRange.location};
			[pagesArray replaceObjectAtIndex:i withObject:[[pagesArray objectAtIndex:i] substringWithRange:tempRange2]];
		}
		[pagesArray removeObjectAtIndex:0];
		for(i=0;i<[pagesArray count];i++)
		{
			NSString *pageLater = [NSString stringWithContentsOfURL:
							  [NSURL URLWithString:
							   [NSString stringWithFormat:@"http://www.literotica.com/stories/showstory.php?id=%@&page=%@",storyID,[pagesArray objectAtIndex:i],nil]]];
			NSRange pageLaterStart	= [pageLater rangeOfString:@"<div id=\"content\">"];
			NSRange pageLaterEnd	= [pageLater rangeOfString:@"<div id=\"storypager\">"];
			NSRange PageLaterRange	= {(pageLaterStart.location+pageLaterStart.length),(pageLaterEnd.location-pageLaterStart.location-pageLaterStart.length) };
			//NSLog(@"1");
			pageLater = [pageLater substringWithRange:PageLaterRange];
			story=[NSString stringWithFormat:@"%@\n\n<br>%@",story,pageLater,nil];
			//NSLog(@"2");
		}
		//[story writeToFile:[[@"/Users/tom/Desktop/newFolder" stringByAppendingPathComponent:storyID] stringByAppendingPathExtension:@"html"] atomically:YES];
		
	} 
	return story;
}
- (void)dealloc
{
	theStoryList	= nil;

	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[theStoryList	release];

	[super dealloc];
}

-(IBAction)doOpenSaveFolder:(id)pId;
{	
	if(!running)
	{
		NSOpenPanel *tvarNSOpenPanelObj	= [NSOpenPanel openPanel];
		[tvarNSOpenPanelObj setMessage:@"Select Folder"];
		[tvarNSOpenPanelObj setCanChooseFiles:NO];
		[tvarNSOpenPanelObj setCanChooseDirectories:YES];
		[tvarNSOpenPanelObj setCanCreateDirectories:YES];
		NSInteger tvarNSInteger	= [tvarNSOpenPanelObj runModalForTypes:nil];
		if(tvarNSInteger == NSOKButton){
			[saveField setStringValue:[tvarNSOpenPanelObj filename]];
			[labelField setStringValue:@"Save Path set"];
		} else if(tvarNSInteger == NSCancelButton) {
			
			return;
		} else {
			return;
		}    
	}
}

-(void)startRunning
{
	running = YES;
	[[NSNotificationCenter defaultCenter] postNotificationName:TCSGRunning object:[NSNumber numberWithBool:YES]];
	[getButton setState:1];
	[saveButton setEnabled:NO];
	[longTOC	setEnabled:NO];
	[hostButton	setEnabled:NO];
	[moreInfoButton		setEnabled:NO];
	[shortTOC	setEnabled:NO];
	[removeButton		setEnabled:NO];
	[compileButton		setEnabled:NO];
	[upButton	setEnabled:NO];
	[downButton	setEnabled:NO];
	[saveField	setEnabled:NO];
	[idField	setEnabled:NO];
}
-(void)stopRunning
{

	running = NO;
	[[NSNotificationCenter defaultCenter] postNotificationName:TCSGRunning object:[NSNumber numberWithBool:NO]];
	[getButton setState:1];
	[saveButton setEnabled:YES];
	[longTOC	setEnabled:YES];
	[hostButton	setEnabled:YES];
	[moreInfoButton		setEnabled:YES];
	[shortTOC	setEnabled:YES];
	[removeButton		setEnabled:YES];
	[compileButton		setEnabled:YES];
	[upButton	setEnabled:YES];
	[downButton	setEnabled:YES];
	[saveField	setEnabled:YES];
	[idField	setEnabled:YES];
}

-(IBAction)doGet:(id)pId
{
	NSString *savePath = [saveField stringValue];
	NSString *IDval=[idField stringValue];
	BOOL isDir;
	if(running) //is it running
	{
		[self stopRunning];
	}
	else //not running yet
	{
		
		if([IDval isEqualToString:@""] || [IDval length] ==0) // is story ID specified
		{
			[labelField setStringValue:@"ERROR: Please specify a story ID"];
		}
		else if([savePath isEqualToString:@""] || [savePath length] ==0) // is there a save path specified
		{
			[labelField setStringValue:@"ERROR: Please specify a Save Path"];
		}
		else	
		{
			if(![[NSFileManager defaultManager] fileExistsAtPath:savePath]) //does folder exist
			{
				running =YES;
				[[NSFileManager defaultManager] createDirectoryAtPath:savePath attributes:nil];
			}
			else if([[NSFileManager defaultManager] fileExistsAtPath:savePath isDirectory:&isDir] && !isDir) // is foldername used
			{
				running=YES;
				[labelField setStringValue:@"ERROR: file already instead of folder at savepath, please move it"];
			}
			
			//Launch Thread
			if([shortTOC state])
			{
				NSThread* myThread = [[NSThread alloc] initWithTarget:self
															 selector:@selector(getAuthorDL:)
															   object:[idField stringValue]];
				[myThread start];

			}
			else
			{
				NSThread* myThread = [[NSThread alloc] initWithTarget:self
															 selector:@selector(getSingleStory:)
															   object:[idField stringValue]];
				[myThread start];

			}
			
			[self startRunning];
			[getButton setState:1];
			
		}
	}
}
-(void)getSingleStory:(NSString *)storyID
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	id get;
	switch ([[hostButton objectValue] intValue]) 
	{
		case 0:
			//NSLog(@"case: 0");
			get = [[TCSGgetSOLstory alloc] init];
			//[self getSOLStory:storyID];
			break;
		case 1:
			//NSLog(@"case: 1");
			[self getStory:storyID];
		break;
		default:
			[labelField setStringValue:@"not implemented yet"];
			break;
	}
	if([get respondsToSelector:@selector(getStory:)])
	{
		NSDictionary *story = [get getStory:storyID];
		[self addStoryToList:story];
	}
	[self stopRunning];
	[getButton setState:0];
	[pool release];
	
}
-(NSDictionary *)getStory:(NSString *)storyID
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	id get;
	switch ([[hostButton objectValue] intValue]) 
	{
		case 0:
			//NSLog(@"case: 0");
			//[self getSOLStory:storyID];
			break;
		case 1:
			//NSLog(@"case: 1");
			[self getLITStory:storyID];
			break;
		default:
			[labelField setStringValue:@"not implemented yet"];
			break;
	}
	[tableView reloadData];
	[pool release];
	//running = NO;
	[tableView scrollRowToVisible:([theStoryList numberOfItems]-1)];
	[labelField setStringValue:@"done"];
	//[theStoryList printDict];
	return nil;
}
- (void)getAuthorDL:(NSString *)authorID
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	id get;
	switch ([[hostButton objectValue] intValue]) 
	{
		case 0:
			//[self sOLAuthorDL:authorID];
			get = [[TCSGgetSOLstory alloc] init];
			break;
		case 1:
			//NSLog(@"case: 1");
			[self getLITAuthor:authorID];
			break;
		default:
			[labelField setStringValue:@"not implemented yet"];
			break;
	}
	NSArray	*authorStories	= [get getStoriesArrayForAuthor:authorID];
	int i;
	for(i=0;i<[authorStories count];i++)
	{
		NSDictionary *storyDict = [get getStory:[authorStories objectAtIndex:i]];
		if(running)
		{
			[self addStoryToList:storyDict];

		}
		if([moreInfoButton state] && running)
		{
			
			[theStoryList addExtraInfo:[get getMoreInfoForID:[authorStories objectAtIndex:i]] forRow:([theStoryList numberOfItems]-1)];
		}
		[tableView reloadData];
	}
	[self stopRunning];
	//[tableView reloadData];
	[pool release];
	
}
- (void)addStoryToList:(NSDictionary *)storyDict
{
	NSArray *keys = [storyDict allKeys];
	if([keys containsObject:STORYKEY] && [keys containsObject:HOSTKEY] && [keys containsObject:AUTHORKEY] && [keys containsObject:IDKEY] && [keys containsObject:TITLEKEY])
	{
		[theStoryList addStory:[storyDict objectForKey:STORYKEY] 
					 withTitle:[storyDict objectForKey:TITLEKEY] 
					withAuthor:[storyDict objectForKey:AUTHORKEY] 
					  withHost:[storyDict objectForKey:HOSTKEY] 
						withID:[storyDict objectForKey:IDKEY] 
					 withCheck:[NSNumber numberWithBool:YES]];
	}
	else
	{
		[TCSGGeneralMethods setLabelField:@"Improperly Formatted Story Dictionary"];
	}
}
/*- (NSArray *)getSOLauthorStoryNumbers:(NSString *)authorName
{
	NSString *authorURL		= [@"http://storiesonline.net/auth/" stringByAppendingPathComponent:authorName];
	NSLog(@"authorURL: %@",authorURL);
	NSString *page1				= [NSString stringWithContentsOfURL:[NSURL URLWithString:authorURL]];
	NSRange rangeStart			= [page1 rangeOfString:@"<h4 id=\"sm-a-head\">"];
	NSRange rangeEnd			= [page1 rangeOfString:@"</h4>"];
	NSRange numberRange;
	NSMutableArray *finalStoriesArray = [[NSMutableArray alloc] init];
	
	if(rangeStart.location==NSNotFound)
	{
		finalStoriesArray = [NSArray arrayWithObject:authorName];
	}
	else
	{
		numberRange.location		= rangeStart.location + rangeStart.length;
		numberRange.length			= rangeEnd.location - numberRange.location;
		NSString *numberOfStories	= [[[page1 substringWithRange:numberRange] componentsSeparatedByString:@" of "] objectAtIndex:1];
		NSLog(@"number of stories: %@, %i",numberOfStories,[numberOfStories intValue]);
		int i = 0;
		int storiesNumber=[numberOfStories intValue];
		while(i*10<storiesNumber)
		{
			//Parse more info (codes/Synopsis)
			NSString *page = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://storiesonline.net/library/author.php?name=%@&sf=story_name&so=asc&skip=%i", authorName,i*10]]];
			//[page writeToFile:[@"~/hello.html" stringByExpandingTildeInPath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
			NSLog(@"%i",i);
			i++;
			NSMutableArray *seperating=[[page componentsSeparatedByString:@"<td class=\"lc2\"><a href=\"/story/"] mutableCopy];
			int z;
			NSLog(@"count: %i",[seperating count]);
			for(z=0;z<[seperating count];z++)
			{
				NSRange stop		=[[seperating objectAtIndex:z] rangeOfString:@"\">"];
				if(stop.location !=NSNotFound || stop.location>15)
				{
					[seperating replaceObjectAtIndex:z withObject:[[seperating objectAtIndex:z] substringToIndex:stop.location]];
				}
				else
				{
					[seperating replaceObjectAtIndex:z withObject:@"000"];
				}
			}
			[seperating removeObjectAtIndex:0];
			[finalStoriesArray addObjectsFromArray:seperating];
			NSLog(@"%@",seperating);
		}
		
	}
	
	return finalStoriesArray;
}
-(void)getSOLStory:(NSString *)storyID
{

	[labelField setStringValue:@"gettingStoryType"];
	NSString *page = [NSString stringWithContentsOfURL:
					  [NSURL URLWithString:
					   [NSString stringWithFormat:@"http://storiesonline.net/story/%@",storyID,nil]]];
	//Title and Author
	NSRange titleStart		= [page rangeOfString:@"<title>"];
	NSRange titleEnd		= [page rangeOfString:@"</title>"];
	NSRange titleRange;
	titleRange.location		= titleStart.location+titleStart.length;
	titleRange.length		= titleEnd.location-titleRange.location;
	NSString *author		= [[[page substringWithRange:titleRange] componentsSeparatedByString:@": "]	objectAtIndex:0];
	NSString *title			= [[[page substringWithRange:titleRange] componentsSeparatedByString:@": "]	objectAtIndex:1];
	if([title rangeOfString:@" (Page 1)"].location!=NSNotFound)
	{
		title = [title substringToIndex:[title rangeOfString:@" (Page 1)"].location];
	}
	
	
	NSRange divdiv = [page rangeOfString:@"</div></div>"];
	NSString *story = [[NSString alloc] init];
	
	if(divdiv.location!=NSNotFound)
	{
		//IndexFound - multiple Chapters
		[labelField setStringValue:@"Multiple Chaptered Story"];
		story = [self getSOLMultipleStory:storyID];
		story = [NSString stringWithFormat:@"<body>\n<h1 class=\"Chapter\">%@</h1><h3 class=\"Author\">%@</h3>\n%@\n</body>",title,author,story,nil];
		NSLog(@"1");
		[self writeLastStoryToFile];
		NSLog(@"2");

	}
	else
	{

		//Title and Author
		NSRange parserRange = [page rangeOfString:@"span class=\"pager\">Pages: Prev"];

		if(parserRange.location != NSNotFound)
		{

			NSString *pagetoo=page;
			BOOL end = FALSE;
			int i=0;
			[labelField setStringValue:@"Single Chapter multiple Part Story"];
			NSRange story1Start	= [pagetoo rangeOfString:@"<p>"];
			NSRange html1End	= [pagetoo rangeOfString:@"</html>"];
			NSRange search1Range;
			search1Range.location= story1Start.location;//+p1s.length;
			search1Range.length	= html1End.location-search1Range.location;
			NSRange story1End	= [pagetoo rangeOfString:@"<span class=\"conTag"];// options:NSCaseInsensitiveSearch range:search1Range];
			NSRange story1Range;
			story1Range.location= story1Start.location;
			story1Range.length	=story1End.location-story1Range.location;
			story = [page substringWithRange:story1Range];

			
			while(end==FALSE)
			{
				i++;
				NSLog(@"loading page : %i",i);
				NSString *page = [NSString stringWithContentsOfURL:
								  [NSURL URLWithString:
								   [NSString stringWithFormat:@"http://storiesonline.net/story/%@;%i",storyID,i,nil]]];
				NSLog(@"loaded");
				NSRange endRange = [page rangeOfString:@"| Next</span><br><br>"];
				NSRange pagerRange	= [page rangeOfString:@"<span class=\"pager\">"];
				NSRange pageEnd		= [page rangeOfString:@"</html>"];
				NSRange searchRange;
				searchRange.location= pagerRange.location+pagerRange.length;
				searchRange.length	= pageEnd.location-searchRange.location;
				NSRange storyEnd	= [page rangeOfString:@"<span class=\"pager\">" options:NSCaseInsensitiveSearch range:searchRange];
				NSRange storyStart	= [page rangeOfString:@"<p>"];
				NSRange pageRange;
				pageRange.location	= storyStart.location;
				pageRange.length	= storyEnd.location-pageRange.location;
				//NSLog(@"%i,%i",pageRange.location,pageRange.length,nil);
				//NSLog(@"%i",[page length]);
				//page = [page substringWithRange:pageRange];
				page = [page substringWithRange:pageRange];
				story = [NSString stringWithFormat:@"%@\n\n<br>%@",story,page];
				if(endRange.location !=NSNotFound)		{end=TRUE;}
					
				
			}
			story = [NSString stringWithFormat:@"<body>\n<h1 class=\"Chapter\">%@</h1><h3 class=\"Author\">%@</h3>\n%@\n</body>",title,author,story,nil];
			
		}
		else
		{
			[labelField setStringValue:@"Single Chapter Story"];
			//Story
			NSRange storyStart		= [page rangeOfString:@"</h4>"];
			NSRange storyEnd		= [page rangeOfString:@"<div id=\"vote-form\">"];
			if(storyEnd.location==NSNotFound)
			{
				storyEnd = [page rangeOfString:@"<h2 class=\"end\""];
			}
			NSRange storyRange;
			storyRange.location		= storyStart.location+storyStart.length;
			storyRange.length		= storyEnd.location-storyRange.location;
			story			= [page substringWithRange:storyRange];
			//Combine
			story = [NSString stringWithFormat:@"<body>\n<h1 class=\"Chapter\">%@</h1><h3 class=\"Author\">%@</h3>\n%@\n</body>",title,author,story,nil];
		}

	}
	if(running)
	{
		[theStoryList addStory:story 
					 withTitle:title 
					withAuthor:author 
					  withHost:@"StoriesOnline"
						withID:storyID 
					 withCheck:[NSNumber numberWithBool:YES]];
		[self writeLastStoryToFile];
	}

	if([moreInfoButton state] && running)
	{
		
		[theStoryList addExtraInfo:[self getSOLMoreInfoForID:storyID] forRow:([theStoryList numberOfItems]-1)];
		
		//NSLog(@"getting More Info: %@",pageInfoArray);
	}
}

- (NSDictionary *)getSOLMoreInfoForID:(NSString *)storyID
{
	NSString *pageInfo = [NSString stringWithContentsOfURL:
						  [NSURL URLWithString:
						   [NSString stringWithFormat:@"http://storiesonline.net/library/storyInfo.php?id=%@",storyID,nil]]];
	NSRange part1 = [pageInfo rangeOfString:@"<td class=\"lc4\">"];
	pageInfo = [pageInfo substringFromIndex:(part1.location +part1.length)];
	NSRange part2 = [pageInfo rangeOfString:@"</td>"];
	pageInfo = [pageInfo substringToIndex:(part2.location)];
	NSArray *pageInfoArray =[pageInfo componentsSeparatedByString:@"<br><b>"];
	int i;
	NSMutableDictionary *extraInfo = [[NSMutableDictionary alloc] init];
	[extraInfo setObject:[[[pageInfoArray objectAtIndex:0] componentsSeparatedByString:@"</b>"] objectAtIndex:0] forKey:@"Summary"];
	for(i=1;i<[pageInfoArray count];i++)
	{
		NSString *tempType = [[[pageInfoArray objectAtIndex:i] componentsSeparatedByString:@"</b>"] objectAtIndex:0];
		NSString *tempString = [[[[pageInfoArray objectAtIndex:i] componentsSeparatedByString:@"</b>"] objectAtIndex:1] substringFromIndex:1];
		//Remove Breaklines

		if([tempString hasSuffix:@"\n"])			{tempString = [tempString substringToIndex:([tempString length]-1)];}
		if([tempType hasSuffix:@":"])				{tempType   = [tempType substringToIndex:([tempType length]-1)];}
		//Fix Posted Problem
		if([tempType isEqualToString:@"Posted"])	{tempString = [[tempString componentsSeparatedByString:@" <br>"] objectAtIndex:0];}
		
		[extraInfo setObject:tempString forKey:tempType];
		
	}
	return extraInfo;
}
				

- (NSString *)getSOLMultipleStory:(NSString *)storyID
{
	//NSLog(@"storyID: %@",storyID);
	NSArray *indexPage = [[NSString stringWithContentsOfURL:
						   [NSURL URLWithString:
							[NSString stringWithFormat:@"http://storiesonline.net/story/%@:i",storyID,nil]]]
						  componentsSeparatedByString:@"<span class=\"link\">"];
	//NSLog(@"indexPage: %@",indexPage);
	NSMutableArray *chapterIDs = [[NSMutableArray alloc] init];
	//NSLog(@"chapterIDs: %@",chapterIDs);
	int i;
	for(i=1;i<[indexPage count];i++)
	{
		NSRange d = [[indexPage objectAtIndex:i] rangeOfString:@":d"];
		[chapterIDs addObject:[[[[indexPage objectAtIndex:i] substringToIndex:d.location] componentsSeparatedByString:@":"] objectAtIndex:1]];
	}
	//NSLog(@"chapterIDs: %@",chapterIDs);
	NSString * story = @"";
	for(i=0;i<[chapterIDs count];i++)
	{
		//NSLog(@"1:%i",i);
		if(running)
		{
			[labelField setStringValue:[NSString stringWithFormat:@"getting chapter: %i",(i+1),nil]];
			NSString *chapter = [self getSOLChapter:[chapterIDs objectAtIndex:i] fromStory:storyID type:0 chapterNumber:(i+1)];
			story = [NSString stringWithFormat:@"%@\n\n\n<br><br>%@",story,chapter];
			
		}
		//NSLog(@"2:%i",i);
	}
	
	[labelField setStringValue:@"multiple done"];
	return story;
}
- (NSString *)getSOLChapter:(NSString *)chapterID fromStory:(NSString *)storyID type:(int)type chapterNumber:(int)number
{
	NSString *page=[NSString stringWithContentsOfURL:
					[NSURL URLWithString:
					 [NSString stringWithFormat:@"http://storiesonline.net/story/%@:%@:d",storyID,chapterID,nil]]];
	NSRange storyStart=[page rangeOfString:@"<p>"];
	NSRange storyEnd = [page rangeOfString:@"<h3 class=\"end\">"];
	if(storyEnd.location == NSNotFound)
	{
		//NSLog(@"not found");
		storyEnd = [page rangeOfString:@"<h2 class=\"end\""];
	}
	NSRange rangeFinal;
	rangeFinal.location = storyStart.location;
	rangeFinal.length = storyEnd.location-rangeFinal.location;
	NSString *tempString = [page substringWithRange:rangeFinal];
	tempString = [NSString stringWithFormat:@"<h2 class=\"chapter\">Chapter %i</h2>\n<br>%@",number,tempString,nil];
	return tempString;
}*/
- (int)numberOfRowsInTableView:(NSTableView *)tv 
{ 
    return [theStoryList numberOfItems]; 
}
- (void)writeLastStoryToFile
{
	//NSLog(@"1.1");
	NSString *story = [theStoryList getLastStory];
	//NSLog(@"1.2");
	NSString *title = [theStoryList getLastTitle];
	//NSLog(@"1.3");
	[story writeToFile:[[saveField stringValue] stringByAppendingPathComponent:[title stringByAppendingPathExtension:@"html"]] atomically:YES encoding:NSUTF8StringEncoding error:nil];
	//NSLog(@"2.1");
}
- (id)tableView:(NSTableView *)tv 
objectValueForTableColumn:(NSTableColumn *)tableColumn 
			row:(int)row 
{ 

	NSArray *columns = [NSArray arrayWithObjects:@"ID",@"Title",@"Author",@"check",@"Host",@"DL",nil];
	long column = [columns indexOfObject:[tableColumn identifier]];
	NSDictionary *storyDict = [theStoryList getDictForRow:row];
	NSString *v;
	switch (column) {
		case 0:
			v=[storyDict objectForKey:IDKEY];
			break;
		case 1:
			v=[storyDict objectForKey:TITLEKEY];
			break;
		case 2:
			v=[storyDict objectForKey:AUTHORKEY];
			break;
		case 4:
			v=[storyDict objectForKey:HOSTKEY];
			break;
		default:
			v=@"";
			break;
	}
    return v; 
} 
- (BOOL)tableView:(NSTableView *)tv 
  shouldTrackCell:(NSCell *)cell 
   forTableColumn:(NSTableColumn *)tableColumn 
			  row:(NSInteger)row
{
	//NSLog(@"tracking: %i",row);
	//NSLog(@"tracking: %@",[tableColumn identifier]);
	BOOL tracking = NO;
	if([[tableColumn identifier] isEqualToString:@"DL"])
	{
		tracking =YES;
		[theStoryList switchCheck:CHECKKEY forRow:row];
		
	}
	return YES;
}

-(void) tableViewSelectionDidChange:(NSNotification *)aNotification
{
	NSLog(@"didchange: %i",[tableView clickedRow]);
}

- (void)tableView:(NSTableView *)tv willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
	if([[aTableColumn identifier] isEqualToString:@"DL"])
	{
		[aCell setState:[self addStory:rowIndex]];
	}
}
- (void)sOLAuthorDL:(NSString *)authorID
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[labelField setStringValue:@"getting Story Numbers"];
	TCSGgetSOLstory *get	= [[TCSGgetSOLstory alloc] init];
	
	NSArray *authorStories = [get getStoriesArrayForAuthor:authorID];//[self getSOLauthorStoryNumbers:authorURL];
	[labelField setStringValue:@"downloading Stories Indexes"];
	//NSLog(@"author stories: \n %@",authorStories);
	[labelField setStringValue:@"DL'ed"];
	int i;
	for(i=0;i<[authorStories count];i++)
	{
		if(running)
		{
			[self getStory:[authorStories objectAtIndex:i]];
		}
	}
	[self stopRunning];
	[getButton setState:0];
	[pool release];
}




-(BOOL)addStory:(int)row	{return [theStoryList checkForRow:row withKey:CHECKKEY];}

-(NSString *)tableView:(NSTableView *)aTableView 
		toolTipForCell:(NSCell *)aCell 
				  rect:(NSRectPointer)rect 
		   tableColumn:(NSTableColumn *)aTableColumn 
				   row:(NSInteger)row 
		 mouseLocation:(NSPoint)mouseLocation
{
	NSString *returnString=@"";
	if([[aTableColumn identifier] isEqualToString:@"DL"])
	{
		returnString = @"Determines if the Story Should be Compiled";
	}
	else
	{
		NSDictionary *tempDict = [theStoryList getDictForRow:row];
		//[tempDict writeToFile:@"/Users/tom/Desktop.plist" atomically:YES];
		if([[tempDict allKeys] containsObject:@"Summary"]){ returnString = [tempDict objectForKey:@"Summary"];/*NSLog(@"returnString: %@",[tempDict objectForKey:@"Summary"]);*/}
		else { returnString = @"Summary Not Available";}
	}
	return returnString;	
}

@end
